package loaders
{
	import flash.display.Loader;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.net.URLRequest;
	import flash.system.LoaderContext;
	
	import memory.MemoryRecovery;
	
	/**
	 * 加载失败的时候自动重新加载的LOADER
	 */ 
	public class AutoRetryLoader extends Loader
	{
	    private var numTries:int=0;
	    private var request:URLRequest;
	    private var maxTries:int=3;
	    private var context:LoaderContext;
		public function AutoRetryLoader(maxTries:int=3)
		{
			super();
			this.maxTries=maxTries;
			initListener();
		}
		private function initListener():void
		{
			this.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR,on_IO_error);
		}
		override public function load(request:URLRequest,context:LoaderContext = null):void
		{
			super.load(request,context);
			this.request=request;
			this.context=context;
		}
		private function reLoad():void
		{
			this.load(request,context);
		}
		private function on_IO_error(e:IOErrorEvent):void
		{
			if(numTries<maxTries)
			{
				try
				{
					this.unload();
					this.close();
				}catch(e:Error)
				{
					
				}
				this.reLoad();
			}else
			{
				trace("AutoRetryLoader放弃加载:"+request.url);
				this.dispatchEvent(new IOErrorEvent(IOErrorEvent.IO_ERROR));
			}
		}
		public function dispose():void
		{
			MemoryRecovery.getInstance().gcFun(this.contentLoaderInfo,IOErrorEvent.IO_ERROR,on_IO_error);
			if(this.parent!=null)
			{
				this.parent.removeChild(this);
			}
			try
			{
				this.unload();
			}catch(e:Error){}
			this.request=null;
			this.context=null;
		}
	}
}